<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <title>分片上传</title>
    <script src="js/spark-md5.min.js"></script>
</head>
<body>
<div class="layui-container">
    <input type="file" id="file" multiple required>
    <button class="layui-btn btnFile" onclick="upload()">立即提交</button>
    <script type="text/javascript">
        // var bytesPerPiece = 1024 * 1024; // 每个文件切片大小定为1MB .
        var bytesPerPiece = 1024; // 每个文件切片大小定为1KB .
        var totalPieces;

        //发送请求
        function upload() {
            var timestamp = getTimestamp();
            var blob = document.getElementById("file").files[0];
            var start = 0;
            var end;
            var index = 0;
            var filesize = blob.size;
            var filename = blob.name;

            //计算文件切片总数
            totalPieces = Math.ceil(filesize / bytesPerPiece);
            while (start < filesize) {
                end = start + bytesPerPiece;
                if (end > filesize) {
                    end = filesize;
                }

                var chunk = blob.slice(start, end);//切割文件
                var sliceIndex = blob.name + index;
                var formData = new FormData();
                formData.append("file", chunk, filename);
                formData.append("orginName", filename);
                formData.append("totalChunks", totalPieces);
                formData.append("curentChunk", index);
                formData.append("timestamp",timestamp);
                $.ajax({
                    url: 'http://localhost:8080/upload',
                    type: 'POST',
                    // cache: false,
                    data: formData,
                    processData: false,
                    contentType: false
                }).done(function (res) {

                }).fail(function (res) {

                });
                start = end;
                index++;
            }
        }

        function getTimestamp() {
            var timestamp = (new Date()).valueOf();
            return timestamp;
        }

    </script>
</div>
</body>
</html>